const sqlOptions = require("../../sql");
const {format} = require("../../utils");
const order = require("express").Router()

// 提交订单
order.post("/save", async (req, res) => {
    try {
        const {list} = req.body

        const date = Date.now()

        // console.log(date)
        const dels = list.map(item => ({
            id: item.shopping_id
        }))

        // console.log(dels)

        await req.db.query(sqlOptions({
            name: "sms_shopping_cart",
            method: "delete",
            data: dels
        }))

        const arr = list.map(item => {
            return {
                order_no: req.base64.encodeNumber(`${item.product_id}-${item.user_id}-${item.shopping_id}-${item.color_id}-${date}`),
                order_status: "0",
                order_count: item.cart_num,
                order_product_total: item.discount ? (item.discount * item.cart_num) : (item.cart_money * item.cart_num),
                user_id: item.user_id
            }
        })
        await req.db.query(sqlOptions({
            name: "oms_order",
            method: "save",
            data: arr
        }))

        const data = arr.map(item => item.order_no)
        return res.status(200).send({
            code: 200,
            message: "提交订单成功",
            data
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 支付总价
order.post("/totalMoney", async (req, res) => {
    try {
        const user_id = req.rows.id
        //oms_shopping_order
        const ids = req.body.ids
        const obligation = req.body.obligation
        // console.log(req.body)
        if (ids) {
            const list = await req.db.query(sqlOptions({
                name: "oms_shopping_order",
                method: "list",
                data: {
                    user_id
                }
            }))

            // console.log(list)

            let i = 0
            for (const item of list) {
                if (item.discount) {
                    i += (item.cart_num * item.discount)
                }else {
                    i += (item.cart_num * item.cart_money)
                }

            }

            const products = list.map(item => {
                if (item.discount) {
                    return {
                        name: item.product_name,
                        money: item.cart_num * item.discount
                    }
                }
                return {
                    name: item.product_name,
                    money: item.cart_num * item.cart_money
                }
            })

            console.log("支付数组",list)
            return res.status(200).send({
                code: 200,
                message: "",
                data: {
                    totalMoney: i,
                    table: products
                }
            })
        }
        if (obligation) {
            const list = await req.db.query(sqlOptions({
                name: "oms_order",
                method: "list",
                data: {
                    user_id
                }
            }))
            const product = await req.db.query(sqlOptions({
                name: "sms_product",
                method: "list",
                data: {}
            }))
            const obligations = list.filter(item => item.order_status === '0')
            const arr = []
            let total = 0
            // req.base64.decodeNumber()
            obligations.forEach(item => {
                total += item.order_product_total;
                const str = req.base64.decodeNumber(item.order_no)
                const strs = str.split("-")
                const obj = {
                    name: product.filter(item => item.product_id === strs[0])[0].product_name,
                    money: item.order_product_total
                }
                arr.push(obj)
            })
            console.log("支付数组",list)
            return res.status(200).send({
                code: 200,
                message: "",
                data: {
                    totalMoney: total,
                    table: arr
                }
            })
        }
    } catch (e) {
        // console.log(e)
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 支付
order.post("/payment", async (req, res) => {
    try {
        const ids = req.body.ids || req.body.obligation
        if (ids) {
            const arr = ids.split(",").map(item => ({
                order_no: item
            }))

            for (const item of arr) {
                const sql = sqlOptions({
                    name: "oms_order",
                    method: "update",
                    data: {
                        order_status: "1"
                    },
                    key: {
                        order_no: item.order_no
                    }
                })
                await req.db.query(sql)
            }
            const user_id = req.rows.id
            const list = await req.db.query(sqlOptions({
                name: "oms_shopping_order",
                method: "list",
                data: {
                    user_id
                }
            }))
            // product_id
            for (const item of list) {
                await req.db.query(`CALL update_row_product_color(${item.cart_num}, ${item.color_id}, '${item.product_id}')`)
                await req.db.query(`UPDATE sms_product SET product_count = product_count - ${item.cart_num} WHERE product_id = '${item.product_id}'`)
                await req.db.query(`UPDATE sms_product SET product_order = product_order + 1 WHERE product_id = '${item.product_id}'`)
                await req.db.query(`UPDATE sms_recommend SET product_count = product_count - ${item.cart_num} WHERE product_id = '${item.product_id}'`)
                await req.db.query(`UPDATE sms_recommend SET product_order = product_order + 1 WHERE product_id = '${item.product_id}'`)
            }

            return res.status(200).send({
                code: 200,
                message: "订单支付成功",
                data: ""
            })
        }
    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})

order.get("/status", async (req, res) => {
    try {
        const user_id = req.rows.id
        const orders = await req.db.query(sqlOptions({
            name: "oms_order",
            method: "list",
            data: {
                user_id
            }
        }))

        const arr = [
            [ "待付款", orders.filter(item => item.order_status === '0').length ],
            [ "待发货", orders.filter(item => item.order_status === '1').length ],
            [ "待收货", orders.filter(item => item.order_status === '2').length ],
            [ "已收货", orders.filter(item => item.order_status === '4').length ]
        ]
        // console.log(arr)

        return res.status(200).send({
            code: 200,
            message: "",
            data: arr
        })
    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// 代付款点击事件
order.get("/obligation", async (req, res) => {
    try {
        const user_id = req.rows.id
        const orders = await req.db.query(sqlOptions({
            name: "oms_order",
            method: "list",
            data: {
                user_id
            }
        }))
        const obligation = orders.filter(item => item.order_status === '0').map(item => item.order_no).join(",")
        return res.status(200).send({
            code: 200,
            message: "",
            data: obligation
        })
    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// 查看物流信息
order.get("/logistics", async (req, res) => {
    try {
        const id = req.rows.id
        const logistics = await req.db.query(sqlOptions({
            name: "oms_order_logistics",
            data: {},
            method: "list"
        }))
        const products = await req.db.query(sqlOptions({
            name: "sms_product",
            data: {},
            method: "list"
        }))

        const orders = await req.db.query(sqlOptions({
            name: "oms_order",
            data: {},
            method: "list"
        }))

        const list = logistics.filter(item => {
            const order_no = req.base64.decodeNumber(item.order_no).split("-")[1]
            return id === Number(order_no)
        }).map(item => {
            const order_no = req.base64.decodeNumber(item.order_no).split("-")[0]
            const product = products.filter(i => i.product_id === order_no)[0]
            const count = orders.filter(i => item.order_no === i.order_no)[0]
            return {
                ...item,
                product_name: product.product_name,
                product_pic: product.product_pic,
                order_count: count.order_count,
                order_product_total: count.order_product_total
            }
        }).filter(item => item.logistics_status !== '13')
        return res.status(200).send({
            code: 200,
            message: "",
            data: list
        })
    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// 确认收货
order.post("/confirm", async (req, res) => {
    try {
        const {
            order_id,
            order_count
        } = req.body
        // 物流表状态更新12
        // 订单表状态更新4
        await req.db.query(sqlOptions({
            name: "oms_order",
            method: "update",
            data: {
                order_status: "4"
            },
            key: {
                id: order_id
            }
        }))
        await req.db.query(sqlOptions({
            name: "oms_order_logistics",
            method: "update",
            data: {
                logistics_status: "13",
                logistics_update_time: format()
            },
            key: {
                order_id
            }
        }))
        // stat 表更新
        const list = await req.db.query(sqlOptions({
            name: 'ums_stat',
            method: "list",
            data: {}
        }))
        if (list.length) {

        } else {
            await req.db.query(sqlOptions({
                name: 'ums_stat',
                method: "save",
                data: {
                    start_order: order_count,
                    start_order_create: format()
                }
            }))
        }

        return res.status(200).send({
            code: 200,
            message: "确认收货",
            data: ''
        })
    } catch (e) {
        console.log(e)
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// 是否退货
order.post("/sales", async (req, res) => {
    try {
        const {
            order_id
        } = req.body
        // 订单表状态更新7 确认退货
        await req.db.query(sqlOptions({
            name: "oms_order",
            method: "update",
            data: {
                order_status: "7"
            },
            key: {
                id: order_id
            }
        }))
        return res.status(200).send({
            code: 200,
            message: "操作成功",
            data: ''
        })
    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// 查看收货信息
order.post("/received", async (req, res) => {
    try {
        const id = req.rows.id
        const logistics = await req.db.query(sqlOptions({
            name: "oms_order_logistics",
            data: {},
            method: "list"
        }))
        const products = await req.db.query(sqlOptions({
            name: "sms_product",
            data: {},
            method: "list"
        }))
        const orders = await req.db.query(sqlOptions({
            name: "oms_order",
            data: {},
            method: "list"
        }))

        // const colors = await req.db.query(sqlOptions({
        //     name: "sms_product_color",
        //     data: {},
        //     method: "list"
        // }))
        // const nos = req.base64.decodeNumber(item.order_no).split("-")

        const list = logistics.filter(item => {
            const order_no = req.base64.decodeNumber(item.order_no).split("-")[1]
            // console.log(order_no)
            // console.log(id)
            return id === Number(order_no)
        }).map(item => {
            const order_no = req.base64.decodeNumber(item.order_no).split("-")[0]
            const product = products.filter(item => item.product_id === order_no)[0]
            const count = orders.filter(i => item.order_no === i.order_no)[0]
            // const color = colors.filter (i => i.product_id === order_no)[0]
            return {
                ...item,
                product_name: product.product_name,
                product_pic: product.product_pic,
                order_count: count.order_count,
                order_product_total: count.order_product_total,
                product_id: product.product_id,
                order_status: count.order_status
            }
        }).filter(item => item.logistics_status === '13')


        return res.status(200).send({
            code: 200,
            message: "",
            data: list
        })

    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

order.post("/received/save", async (req, res) => {
    try {
        const {id: user_id, username} = req.rows
        const {product_id, remark} = req.body
        await req.db.query(sqlOptions({
            name: "oms_product_comment",
            method: "save",
            data: {
                user_id,
                username,
                product_id,
                remark
            }
        }))
        return res.status(200).send({
            code: 200,
            message: "评论成功",
            data: ''
        })
    } catch (e) {
        return res.status(200).send({
            code: 500,
            message: "系统错误",
            data: ''
        })
    }
})

// masiro.me
module.exports = order

// 物流更新, 评价, 退货, 统计:退货 日期购买, 折扣
/**
 * 物流更新完成
 * 评价完成
 * 退货, 前台完成, 后台为完成
 * 折扣
 * 统计
 */
